import { useUserStore } from '@/stores';
import { checkPermissions } from '@/utils/permission';
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/login/LoginPage.vue') },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      children: [
        {
          path: '/audit',
          component: () => import('@/views/audit/AuditContainer.vue'),
        },
        {
          path: '/account',
          component: () => import('@/views/account/AccountContainer.vue'),
        }
      ]
    }
  ]
})

// 配置路由权限映射表
const routePermissions = {
  '/audit': 'AUDIT:SELECT',
  '/account': 'ACCOUNT:SELECT'
}

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  if (userStore.getPermissions().length === 0) {
    await userStore.updatePermissions()
  }
  // 获取当前路由需要的权限
  const requiredPermission = routePermissions[to.path]

  // 不需要权限的路由直接放行
  if (!requiredPermission) {
    return next()
  }

  // 统一权限检查逻辑
  if (!checkPermissions(requiredPermission)) {
    ElMessage.error("你没有操作权限！")
    return next(false)
  }
  next()
})

export default router
